document.addEventListener('DOMContentLoaded', () => {
    const bucketList = document.getElementById('bucket-list');
    const fileList = document.getElementById('file-list');
    const currentBucketTitle = document.getElementById('current-bucket-title');
    const loader = document.getElementById('loader');
    const selectAllCheckbox = document.getElementById('select-all');
    const batchActions = document.getElementById('batch-actions');
    const batchDeleteBtn = document.getElementById('batch-delete-btn');
    const selectedCount = document.getElementById('selected-count');

    let activeBucket = null;
    let selectedFiles = new Set();

    // --- Helper Functions ---

    function showLoader() {
        loader.classList.remove('hidden');
    }

    function hideLoader() {
        loader.classList.add('hidden');
    }

    function formatBytes(bytes, decimals = 2) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const dm = decimals < 0 ? 0 : decimals;
        const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    }

    function formatTimestamp(timestamp) {
        // 七牛云时间戳是 100纳秒 单位，需要转换为毫秒
        const date = new Date(timestamp / 10000);
        return date.toLocaleString();
    }

    function updateSelectedCount() {
        const count = selectedFiles.size;
        selectedCount.textContent = `已选择 ${count} 个文件`;
        
        if (count > 0) {
            batchActions.classList.remove('hidden');
            batchDeleteBtn.disabled = false;
        } else {
            batchActions.classList.add('hidden');
            batchDeleteBtn.disabled = true;
        }
    }

    function toggleFileSelection(fileKey, checkbox) {
        if (checkbox.checked) {
            selectedFiles.add(fileKey);
            checkbox.closest('tr').classList.add('selected');
        } else {
            selectedFiles.delete(fileKey);
            checkbox.closest('tr').classList.remove('selected');
        }
        updateSelectedCount();
        updateSelectAllState();
    }

    function updateSelectAllState() {
        const allCheckboxes = document.querySelectorAll('.file-checkbox');
        const checkedCheckboxes = document.querySelectorAll('.file-checkbox:checked');
        
        if (checkedCheckboxes.length === 0) {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = false;
        } else if (checkedCheckboxes.length === allCheckboxes.length) {
            selectAllCheckbox.indeterminate = false;
            selectAllCheckbox.checked = true;
        } else {
            selectAllCheckbox.indeterminate = true;
            selectAllCheckbox.checked = false;
        }
    }

    function clearSelection() {
        selectedFiles.clear();
        document.querySelectorAll('.file-checkbox').forEach(checkbox => {
            checkbox.checked = false;
            checkbox.closest('tr').classList.remove('selected');
        });
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
        updateSelectedCount();
    }

    // --- API Calls ---

    async function fetchBuckets() {
        try {
            const response = await fetch('/api/buckets');
            if (!response.ok) throw new Error('Failed to fetch buckets');
            const data = await response.json();
            renderBuckets(data.buckets);
        } catch (error) {
            console.error(error);
            alert('获取存储空间列表失败！');
        }
    }

    async function fetchFiles(bucketName) {
        showLoader();
        fileList.innerHTML = '';
        currentBucketTitle.textContent = `正在加载: ${bucketName}...`;
        try {
            // 添加all=true参数获取全部文件
            const response = await fetch(`/api/files?bucket=${encodeURIComponent(bucketName)}&all=true`);
            if (!response.ok) throw new Error('Failed to fetch files');
            const data = await response.json();
            const files = data.items || [];
            renderFiles(files);
            currentBucketTitle.textContent = `空间: ${bucketName} (${files.length} 个文件)`;
            
            // 更新当前选中bucket的文件数量显示
            if (activeBucket) {
                const countElement = activeBucket.querySelector('.bucket-file-count');
                if (countElement) {
                    countElement.textContent = `${files.length} 个文件`;
                }
            }
        } catch (error) {
            console.error(error);
            alert(`获取文件列表失败: ${error.message}`);
            currentBucketTitle.textContent = `无法加载 ${bucketName} 的文件`;
        } finally {
            hideLoader();
        }
    }

    async function fetchFileCount(bucket, bucketElement) {
        try {
            // 添加all=true参数获取全部文件
            const response = await fetch(`/api/files?bucket=${encodeURIComponent(bucket)}&all=true`);
            const data = await response.json();
            const files = data.items || [];
            const countElement = bucketElement.querySelector('.bucket-file-count');
            if (countElement) {
                countElement.textContent = `${files.length} 个文件`;
            }
        } catch (error) {
            console.error(`获取 ${bucket} 文件数量失败:`, error);
            const countElement = bucketElement.querySelector('.bucket-file-count');
            if (countElement) {
                countElement.textContent = '获取失败';
            }
        }
    }

    async function deleteFile(bucket, key) {
        if (!confirm(`确定要删除文件 "${key}" 吗？此操作不可恢复！`)) {
            return;
        }
        try {
            const response = await fetch('/api/files', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ bucket, key }),
            });
            const result = await response.json();
            if (!response.ok) {
                throw new Error(result.error || '删除失败');
            }
            alert('文件删除成功！');
            // Refresh file list
            fetchFiles(bucket);
        } catch (error) {
            console.error(error);
            alert(`删除文件失败: ${error.message}`);
        }
    }

    async function batchDeleteFiles(bucket, keys) {
        if (!confirm(`确定要删除选中的 ${keys.length} 个文件吗？此操作不可恢复！`)) {
            return;
        }
        
        showLoader();
        batchDeleteBtn.disabled = true;
        batchDeleteBtn.textContent = '删除中...';
        
        try {
            const response = await fetch('/api/files/batch', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ bucket, keys }),
            });
            const result = await response.json();
            if (!response.ok) {
                throw new Error(result.error || '批量删除失败');
            }
            alert(`成功删除 ${keys.length} 个文件！`);
            clearSelection();
            // Refresh file list
            fetchFiles(bucket);
        } catch (error) {
            console.error(error);
            alert(`批量删除失败: ${error.message}`);
        } finally {
            hideLoader();
            batchDeleteBtn.disabled = false;
            batchDeleteBtn.textContent = '删除选中文件';
        }
    }

    // --- Rendering ---

    function renderBuckets(buckets) {
        bucketList.innerHTML = '';
        // 后端已经处理好，直接是名称数组
        buckets.forEach(bucket => {
            const li = document.createElement('li');
            li.innerHTML = `
                <span class="bucket-name">${bucket}</span>
                <span class="bucket-file-count">加载中...</span>
            `;
            li.dataset.bucketName = bucket;
            li.addEventListener('click', () => {
                if (activeBucket) {
                    activeBucket.classList.remove('active');
                }
                li.classList.add('active');
                activeBucket = li;
                fetchFiles(bucket);
            });
            bucketList.appendChild(li);
            
            // 异步获取文件数量
            fetchFileCount(bucket, li);
        });
    }

    function renderFiles(files) {
        fileList.innerHTML = '';
        clearSelection(); // Clear previous selection
        
        if (files.length === 0) {
            const tr = document.createElement('tr');
            const td = document.createElement('td');
            td.colSpan = 5; // Updated colspan for new checkbox column
            td.textContent = '这个空间是空的。';
            tr.appendChild(td);
            fileList.appendChild(tr);
            return;
        }
        
        // 按文件大小从大到小排序
        files.sort((a, b) => b.fsize - a.fsize);

        files.forEach(file => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><input type="checkbox" class="file-checkbox" data-key="${file.key}"></td>
                <td>${file.key}</td>
                <td>${formatBytes(file.fsize)}</td>
                <td>${formatTimestamp(file.putTime)}</td>
                <td>
                    <button class="copy-link-btn" data-key="${file.key}" title="复制链接">📋</button>
                    ${isImageFile(file.key) ? `<button class="preview-btn" data-key="${file.key}" title="预览图片">👁️</button>` : ''}
                    <button class="delete-btn" data-key="${file.key}">删除</button>
                </td>
            `;
            
            // Add checkbox event listener
            const checkbox = tr.querySelector('.file-checkbox');
            checkbox.addEventListener('change', (e) => {
                toggleFileSelection(file.key, e.target);
            });
            
            // Add copy link button event listener
            const copyBtn = tr.querySelector('.copy-link-btn');
            if (copyBtn) {
                copyBtn.addEventListener('click', (e) => {
                    const key = e.target.dataset.key;
                    const bucket = activeBucket.dataset.bucketName;
                    copyFileLink(bucket, key);
                });
            }
            
            // Add preview button event listener
            const previewBtn = tr.querySelector('.preview-btn');
            if (previewBtn) {
                previewBtn.addEventListener('click', (e) => {
                    const key = e.target.dataset.key;
                    const bucket = activeBucket.dataset.bucketName;
                    previewImage(bucket, key);
                });
            }
            
            // Add delete button event listener
             tr.querySelector('.delete-btn').addEventListener('click', (e) => {
                 const key = e.target.dataset.key;
                 const bucket = activeBucket.dataset.bucketName;
                 deleteFile(bucket, key);
             });
            
            fileList.appendChild(tr);
        });
    }

    // 判断是否为图片文件
    function isImageFile(filename) {
        const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
        const ext = filename.toLowerCase().substring(filename.lastIndexOf('.'));
        return imageExtensions.includes(ext);
    }
    
    // 复制文件链接
    async function copyFileLink(bucket, key) {
        try {
            const response = await fetch(`/api/bucket/domain?bucket=${encodeURIComponent(bucket)}`);
            const data = await response.json();
            
            if (data.success && data.domain && data.domain.domain) {
                const fileUrl = `http://${data.domain.domain}/${encodeURIComponent(key)}`;
                await navigator.clipboard.writeText(fileUrl);
                showMessage('链接已复制到剪贴板', 'success');
            } else {
                showMessage(data.error || '获取域名失败', 'error');
            }
        } catch (error) {
            console.error('复制链接失败:', error);
            showMessage('复制链接失败', 'error');
        }
    }
    
    // 预览图片
    async function previewImage(bucket, key) {
        try {
            const response = await fetch(`/api/bucket/domain?bucket=${encodeURIComponent(bucket)}`);
            const data = await response.json();
            
            if (data.success && data.domain && data.domain.domain) {
                const imageUrl = `http://${data.domain.domain}/${encodeURIComponent(key)}`;
                showImagePreview(imageUrl, key);
            } else {
                showMessage(data.error || '获取域名失败', 'error');
            }
        } catch (error) {
            console.error('预览图片失败:', error);
            showMessage('预览图片失败', 'error');
        }
    }
    
    // 显示图片预览模态框
    function showImagePreview(imageUrl, filename) {
        // 创建模态框
        const modal = document.createElement('div');
        modal.className = 'image-preview-modal';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3>${filename}</h3>
                    <button class="close-btn">&times;</button>
                </div>
                <div class="modal-body">
                    <img src="${imageUrl}" alt="${filename}" class="preview-image">
                </div>
            </div>
        `;
        
        // 添加关闭事件
        modal.addEventListener('click', (e) => {
            if (e.target === modal || e.target.classList.contains('close-btn')) {
                document.body.removeChild(modal);
            }
        });
        
        document.body.appendChild(modal);
    }
    
    // 显示消息提示
    function showMessage(message, type = 'info') {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        messageDiv.textContent = message;
        
        document.body.appendChild(messageDiv);
        
        setTimeout(() => {
            if (document.body.contains(messageDiv)) {
                document.body.removeChild(messageDiv);
            }
        }, 3000);
    }

    // --- Event Listeners ---
    
    // Select all checkbox
    selectAllCheckbox.addEventListener('change', (e) => {
        const checkboxes = document.querySelectorAll('.file-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = e.target.checked;
            toggleFileSelection(checkbox.dataset.key, checkbox);
        });
    });
    
    // Batch delete button
    batchDeleteBtn.addEventListener('click', () => {
        if (selectedFiles.size > 0 && activeBucket) {
            const bucket = activeBucket.dataset.bucketName;
            const keys = Array.from(selectedFiles);
            batchDeleteFiles(bucket, keys);
        }
    });

    // --- Initial Load ---
    fetchBuckets();
});
